package com.aoxun.core.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ArrayUtils;

import com.baomidou.mybatisplus.toolkit.StringUtils;

/**
 * cookie工具类
 * @author zcj
 *
 */
public class CookieUtil {
	
	/**
	 * 根据cookie key获取value
	 * @param request
	 * @param response
	 * @param cookieKey
	 * @return
	 */
	public static String getCookieValueByKey(HttpServletRequest request,HttpServletResponse response,String cookieKey) {
		
		if (request == null || StringUtils.isEmpty(cookieKey)) {
			return null;
		}

		Cookie[] cookies = request.getCookies();
		if (ArrayUtils.isEmpty(cookies)) {
			return null;
		}
		
		for(Cookie cookie : cookies) {
			if (cookieKey.equals(cookie.getName())) {
				return cookie.getValue();
			}
		}
		return null;
	}
	
	/**
	 * 往response中添加cookie
	 * @param request
	 * @param response
	 * @param cookieKey
	 * @param cookieValue
	 */
	public static void addCookie(HttpServletRequest request,HttpServletResponse response,String cookieKey,String cookieValue) {
		
		if (StringUtils.isEmpty(cookieKey) || StringUtils.isEmpty(cookieValue)) {
			return;
		}
		Cookie cookie = new Cookie(cookieKey,cookieValue);
		response.addCookie(cookie);
	}
	
	/**
	 * 移除cookie
	 * @param request
	 * @param response
	 * @param cookieKey
	 */
	public static void removeCookie(HttpServletRequest request,HttpServletResponse response,String cookieKey) {
		if (StringUtils.isEmpty(cookieKey)) {
			return;
		}
		Cookie cookie = new Cookie(cookieKey,null);
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}

}
